﻿using AutoMapper;
using ETA.Dtos;
using ETA.Entity;
using ETA.IRepository;
using ETA.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ETA.Common;
using System.Linq.Expressions;
using System.Web;
using CentaLine.Infrastructure;
using ETA.ExtendEntity;
namespace ETA.Service
{
    public class UserService : IUserService
    {
        #region 属性

        private IUserRepository _IUserRepository { set; get; }
        private IRolerRepository _IRolerRepository { set; get; }
        private IRegistrationMainFormRepository _IRegistrationMainFormRepository { set; get; }

        #endregion

        #region 构造函数

        public UserService(IUserRepository IUserRepository, IRolerRepository IRolerRepository, IRegistrationMainFormRepository IRegistrationMainFormRepository)
        {
            _IUserRepository = IUserRepository;
            _IRolerRepository = IRolerRepository;
            _IRegistrationMainFormRepository = IRegistrationMainFormRepository;
        }

        #endregion


        /// <summary>
        /// 创建一个用户
        /// </summary>
        /// <param name="createUserRequest"></param>
        /// <returns></returns>
        public CreateUserResponse AddUser(CreateUserRequest createUserRequest, bool needCheck = true)
        {
            var response = new CreateUserResponse();

            var err = string.Empty;

            if (CheckLoginName(createUserRequest.UserDto.LoginName))
            {
                err += "该用户名已经被其他用户使用";
            }

            if (CheckEmail(createUserRequest.UserDto.Email) && needCheck)
            {
                err += "该邮箱已经被其他用户使用";
            }
            if (CheckMobile(createUserRequest.UserDto.Mobile) && needCheck)
            {
                err += "该手机号码已经被其他用户使用";
            }
            if (!string.IsNullOrEmpty(err))
            {
                response.Result.IsSuccess = false;
                response.Result.ErrMessage = err;
                return response;
            }
            try
            {
                var user = Mapper.Map<UserDto, User>(createUserRequest.UserDto);
                if (!string.IsNullOrEmpty(user.Password))
                {
                    user.Password = CommHelper.Base64Encrypt(user.Password.Trim());
                }
                user.UserId = GenerateNo("U", 1);
                _IUserRepository.Insert(user);
                response.Result.IsSuccess = true;
                response.User = user;
                var userDtoReturn = Mapper.Map<User, UserDto>(user);
                response.UserDto = userDtoReturn;
                //如果是实习生创建一条流程信息
                if (user.Rolers.Any(r => r.RolerName == "实习生"))
                {
                    var form = new RegistrationMainForm
                    {
                        RegistrationMainFormId = Guid.NewGuid() + "",
                        User = user
                    };
                    var rep = _IRegistrationMainFormRepository.Merge(form);
                }
            }
            catch (Exception e)
            {
                response.Result.IsSuccess = false;
                response.Result.ErrMessage = e.Message;
            }
            return response;
        }


        /// <summary>
        /// 检测手机号码是否已被使用
        /// </summary>
        /// <param name="mobile"></param>
        public bool CheckLoginName(string loginName)
        {
            var req = new QueryUserRequest
            {
                User = new User
                {
                    LoginName = loginName
                }
            };
            var response = this.QueryUser(req);
            if (response.Result.IsSuccess && response.Users.Any())
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 检测手机号码是否已被使用
        /// </summary>
        /// <param name="mobile"></param>
        public bool CheckMobile(string mobile)
        {
            var req = new QueryUserRequest
            {
                User = new User
                {
                    Mobile = mobile
                }
            };
            var response = this.QueryUser(req);
            if (response.Result.IsSuccess && response.Users.Any())
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 检测邮箱是否已被使用
        /// </summary>
        /// <param name="mobile"></param>
        public bool CheckEmail(string email)
        {
            var req = new QueryUserRequest
            {
                User = new User
                {
                    Email = email
                }
            };
            var response = this.QueryUser(req);
            if (response.Result.IsSuccess && response.Users.Any())
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 验证码发送
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns>发送成功返回字符，失败返回空串</returns>
        public string SendCheckNum(string mobile, string identifyCode = null)
        {
            var rnd = new Random();
            var num = string.Empty;
            if (!string.IsNullOrEmpty(identifyCode))
            {
                num = identifyCode;
            }
            else
            {
                num = rnd.Next(1000, 2000) + "";
            }
            //TODO 测试
            var res = CommHelper.SendMsg(mobile, String.Format(Config.SMSRegistContent, num));
            if (true)
            {
                return num + "";
            }
            return "";
        }
        /// <summary>
        /// 返回角色列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public QueryRolerResponse QueryRoler(QueryRolerRequest request)
        {

            var key = "keyAllRoles";
            if (CacheHelper.Get(key) != null)
            {
                return CacheHelper.Get(key) as QueryRolerResponse;
            }

            var response = new QueryRolerResponse();

            if (!string.IsNullOrEmpty(request.RolerId))
            {
                var rolerList = _IRolerRepository.Query(r => r.Where(t => t.RolerId == request.RolerId));
                response.Rolers = rolerList;
                response.Result.IsSuccess = true;
            }
            else
            {
                var rolerList = _IRolerRepository.GetAllList();
                response.Rolers = rolerList;
                response.Result.IsSuccess = true;
                CacheHelper.AddDays(key, response, 30);
            }
            return response;
        }

        /// <summary>
        /// 用户信息查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public QueryUserResponse QueryUser(QueryUserRequest request)
        {
            var response = new QueryUserResponse();

            if (request != null)
            {
                var express = QueryUserExpress(request);
                var userList = _IUserRepository.GetAllList(express);
                response.Users = userList;
                response.DtoUsers = AutoMapper.Mapper.Map<List<User>, List<UserDto>>(userList);
                if (userList.Any())
                {
                    if (userList.First().RegistrationMainForms != null && userList.First().RegistrationMainForms.Any())
                    {
                        var mainformId = userList.FirstOrDefault().RegistrationMainForms.First().RegistrationMainFormId;

                        if (mainformId != null)
                        {
                            response.DtoUsers.First().RegistrationMainFormId = mainformId;
                        }
                    }
                }
                response.Result.IsSuccess = true;
            }
            else
            {
                response.Result.IsSuccess = false;
                response.Result.ErrMessage = "请求参数为空";
            }
            return response;
        }

        public int QueryUserCount(QueryUserRequest request)
        {
            var count = 0;
            if (request != null)
            {
                var express = QueryUserExpress(request);
                var userList = _IUserRepository.GetAllList(express);
                count = userList.Count;
            }
            return count;
        }

        private Expression<Func<User, bool>> QueryUserExpress(QueryUserRequest request)
        {
            Expression<Func<User, bool>> express = user => true;
            if (!string.IsNullOrEmpty(request.User.Mobile))
            {
                express = user => user.Mobile == request.User.Mobile && request.User.IsDelete == false;
            }
            else
                if (!string.IsNullOrEmpty(request.User.Email))
                {
                    express = user => user.Email == request.User.Email && request.User.IsDelete == false;
                }
                else
                    if (!string.IsNullOrEmpty(request.User.LoginName))
                    {
                        express = user => user.LoginName == request.User.LoginName && request.User.IsDelete == false;
                    }
                    else
                        if (!string.IsNullOrEmpty(request.User.UserId))
                        {
                            express = user => user.UserId == request.User.UserId && request.User.IsDelete == false;
                        }

            if (!string.IsNullOrEmpty(request.RolerId))
            {
                express = user => user.Rolers.Any(r => r.RolerId == request.RolerId);
            }

            return express;
        }



        public ModifyUserResponse ModifyUser(ModifyUserRequest request)
        {
            var res = new ModifyUserResponse();
            try
            {
                if (request != null)
                {
                    _IUserRepository.Merge(request.User);
                    res.Result.IsSuccess = true;
                }
            }
            catch (Exception e)
            {
                res.Result.IsSuccess = false;
                res.Result.ErrMessage = e.Message;
            }
            return res;
        }

        /// <summary>
        /// 找回密码
        /// </summary>
        /// <param name="strNum"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public Response GetPassword(string strNum, DomainEnum.GetpwdType type)
        {
            var res = new Response();
            var user = new User();
            if (type == DomainEnum.GetpwdType.mobile)
            {
                user.Mobile = strNum;
            }
            else if (type == DomainEnum.GetpwdType.email)
            {
                user.Email = strNum;
            }

            var response = this.QueryUser(new QueryUserRequest { User = user });
            if (response.Result.IsSuccess)
            {
                if (response.Users.Any())
                {
                    var pwd = response.Users.First().Password;
                    pwd = CommHelper.Base64Dencrypt(pwd);
                    if (type == DomainEnum.GetpwdType.mobile)
                    {
                        var sendRes = CommHelper.SendMsg(strNum, String.Format(Config.SMSGetpwdContent, pwd));
                        if (sendRes)
                        {
                            res.Result.IsSuccess = true;
                        }
                        else
                        {
                            res.Result.ErrMessage = "短信发送失败,请稍后重试";
                        }
                    }
                    else
                    {
                        var sendRes = CommHelper.SendEmail(strNum, String.Format(Config.SMSGetpwdContent, pwd), "找回密码");

                        if (sendRes)
                        {
                            res.Result.IsSuccess = true;
                        }
                        else
                        {
                            res.Result.ErrMessage = "邮件发送失败,请稍后重试";
                        }
                    }
                }
                else
                {
                    res.Result.ErrMessage = "用户信息不存在";
                }
            }
            return res;
        }

        #region IUserService 成员


        public string GenerateNo(string firestChar, int noType)
        {
            return _IUserRepository.GenerateNo(firestChar, noType);
        }

        #endregion


        public List<UserView> GetFilterUser(out int rowCount, UserFilter filter)
        {
            return _IUserRepository.GetFilterUser(out rowCount, filter);
        }


        public bool UpdateUserIsReferrer(string userId, int isReferrer)
        {
            return _IUserRepository.UpdateUserIsReferrer(userId, isReferrer);
        }
    }
}
